﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI.WebControls;
using RssReader.Core.BL;

namespace RssReader.Core.UI
{
	public class UriListControl : BaseControl
	{
		#region Private Properties
		private Repeater _rpUriList;
		private TextBox _tbUriName;
		private TextBox _tbUriPath;
		private LinkButton _lbSave;
		#endregion

		#region Public Properties

		#endregion

		#region Constructors

		#endregion

		#region Private Methods
		protected override void OnInit(EventArgs e)
		{
			base.OnInit(e);
			this.NeedLogin = true;
			this.DataBind();
		}
		protected override void AttachChildControls()
		{
			_rpUriList = this.FindControl("rpUriList") as Repeater;
			_tbUriPath = this.FindControl("tbUriPath") as TextBox;
			_tbUriName = this.FindControl("tbUriName") as TextBox;
			_lbSave = this.FindControl("lbSave") as LinkButton;
			_rpUriList.ItemDataBound += new RepeaterItemEventHandler(_rpUriList_ItemDataBound);
			_rpUriList.ItemCommand += new RepeaterCommandEventHandler(_rpUriList_ItemCommand);
			_lbSave.Click += new EventHandler(_lbSave_Click);

			BindListData();
		}

		private void BindListData()
		{
			_rpUriList.DataSource = this.CurrentUser.UriList;
			_rpUriList.DataBind();
		}

		void _lbSave_Click(object sender, EventArgs e)
		{
			string path = _tbUriPath.Text;
			string name = _tbUriName.Text;
			if (Validation.Instance.IsEmpty(name))
			{
				this.ThrowError("name can not be null");
			}
			else if (Validation.Instance.IsEmpty(path))
			{
				this.ThrowError("path can not be null");
			}
			else
			{
				this.CurrentUser.AddUri(path, name);
				_tbUriPath.Text = string.Empty;
				BindListData();
			}
		}

		void _rpUriList_ItemDataBound(object sender, RepeaterItemEventArgs e)
		{
			if (e.Item.DataItem is UriPath)
			{
				UriPath up = e.Item.DataItem as UriPath;
				Literal litPath = e.Item.FindControl("litPath") as Literal;
				litPath.Text = up.Name;
				LinkButton lbDel = e.Item.FindControl("lbDel") as LinkButton;
				lbDel.CommandArgument = up.Path;
				lbDel.CommandName = "del";
				LinkButton lbUri = e.Item.FindControl("lbUri") as LinkButton;
				lbUri.CommandArgument = up.Path;
				lbUri.CommandName = "navigate";
			}
		}

		void _rpUriList_ItemCommand(object source, RepeaterCommandEventArgs e)
		{
			switch (e.CommandName)
			{
				case "del":
					string path = e.CommandArgument.ToString();
					this.CurrentUser.DeleteUri(path);
					this.BindListData();
					break;
				case "navigate":
					this.Context.Items["UriPath"] = (e.CommandSource as LinkButton).CommandArgument;
					break;
			}
		}
		#endregion

		#region Public Methods

		#endregion
	}
}
